<template>
  <view class="address-add-page">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 自定义导航栏 -->
    <view class="custom-nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="nav-back" @click="goBack">
        <uni-icons type="left" size="20" color="#333333"></uni-icons>
      </view>
      <view class="nav-title">{{ isEdit ? '地址编辑' : '地址添加' }}</view>
    </view>

    <!-- 内容区域 -->
    <scroll-view class="content-scroll" scroll-y>
      <!-- 地址信息表单 -->
      <view class="form-container">
        <!-- 收货人 -->
        <view class="form-item">
          <view class="form-label">收货人:</view>
          <input
            class="form-input"
            v-model="formData.name"
            placeholder="请输入收货人姓名"
            placeholder-style="color: #cbcbcb; font-size: 28rpx; font-weight: 350;"
          />
        </view>

        <!-- 手机号码 -->
        <view class="form-item">
          <view class="form-label">手机号码:</view>
          <input
            class="form-input"
            v-model="formData.tel"
            type="number"
            maxlength="11"
            placeholder="请输入收货人手机号"
            placeholder-style="color: #cbcbcb; font-size: 28rpx; font-weight: 350;"
            @blur="onTelBlur"
          />
        </view>

        <!-- 所在地区 -->
        <view class="form-item">
          <view class="form-label">所在地区:</view>
          <input
            class="form-input"
            v-model="formData.address"
            placeholder="请输入收货人地址"
            placeholder-style="color: #cbcbcb; font-size: 28rpx; font-weight: 350;"
          />
          <view class="location-btn" @click="openLocation">
            <image class="location-icon" :src="public_img + '/img/position.png'" mode="aspectFit"></image>
            <text class="location-text">定位</text>
          </view>
        </view>

        <!-- 详细地址 -->
        <view class="form-item">
          <view class="form-label">详细地址:</view>
          <input
            class="form-input"
            v-model="formData.desc"
            placeholder="街道、楼牌号"
            placeholder-style="color: #cbcbcb; font-size: 28rpx; font-weight: 350;"
          />
        </view>
      </view>

      <!-- 默认地址设置 -->
      <view class="default-switch">
        <text class="switch-label">设置为默认地址</text>
        <switch
          :checked="formData.default === '1'"
          @change="onDefaultChange"
          color="#ff0000"
          style="transform: scale(0.8);"
        />
      </view>
    </scroll-view>

    <!-- 底部保存按钮 -->
    <view class="save-btn" @click="handleSave">
      <text class="save-btn-text">保存</text>
    </view>
  </view>
</template>

<script>
import { addressApi } from '@/api/indexAPI.js';
import { public_img } from '@/static/public.js';

export default {
  data() {
    return {
      statusBarHeight: 0,
      public_img: public_img,
      isEdit: false,
      addressId: null,
      formData: {
        name: '',
        tel: '',
        address: '',
        desc: '',
        default: '0' // 0不是默认，1是默认
      }
    };
  },
  onLoad(options) {
    this.getStatusBarHeight();
    
    // 判断是编辑还是新增
    if (options.id) {
      this.isEdit = true;
      this.addressId = options.id;
      this.loadAddressDetail(options.id);
    } else {
      this.isEdit = false;
    }
  },
  methods: {
    // 获取状态栏高度
    getStatusBarHeight() {
      try {
        const systemInfo = uni.getSystemInfoSync();
        this.statusBarHeight = systemInfo.statusBarHeight || 0;
      } catch (err) {
        console.error('获取状态栏高度失败', err);
        this.statusBarHeight = 20;
      }
    },
    // 手机号输入失焦校验
    onTelBlur() {
      if (!this.formData.tel) return;
      const telReg = /^1[3-9]\d{9}$/;
      if (!telReg.test(this.formData.tel)) {
        uni.showToast({
          title: '手机号格式不正确',
          icon: 'none'
        });
      }
    },
    // 返回
    goBack() {
      uni.navigateBack();
    },
    // 加载地址详情（编辑模式）
    async loadAddressDetail(id) {
      try {
        const res = await addressApi.getAddressList();
        console.log("获取地址列表:", res);
        
        if (res.code === 1 && res.data && Array.isArray(res.data)) {
          const address = res.data.find(item => item.id == id);
          if (address) {
            // 回显数据
            this.formData = {
              name: address.name || '',
              tel: address.tel || '',
              address: address.address || '',
              desc: address.desc || '',
              // 统一为字符串，确保与开关绑定判断一致
              default: String(address.default ?? '0')
            };
          } else {
            uni.showToast({
              title: '地址不存在',
              icon: 'none'
            });
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          }
        } else {
          uni.showToast({
            title: '获取地址信息失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error("获取地址详情异常:", error);
        uni.showToast({
          title: '获取地址信息失败',
          icon: 'none'
        });
      }
    },
    // 默认地址开关变化
    onDefaultChange(e) {
      this.formData.default = e.detail.value ? '1' : '0';
    },
    // 打开定位页面
    openLocation() {
      uni.navigateTo({
        url: '/pages/location/position',
        events: {
          // 接收定位页回传的数据
          locationSelected: (data) => {
            if (data && data.address) {
              this.formData.address = data.address;
              this.formData.desc = data.name || '';
            }
          }
        }
      });
    },
    // 表单验证
    validateForm() {
      if (!this.formData.name || this.formData.name.trim() === '') {
        uni.showToast({
          title: '请输入收货人姓名',
          icon: 'none'
        });
        return false;
      }
      if (!this.formData.tel || this.formData.tel.trim() === '') {
        uni.showToast({
          title: '请输入手机号码',
          icon: 'none'
        });
        return false;
      }
      // 验证手机号格式
      const telReg = /^1[3-9]\d{9}$/;
      if (!telReg.test(this.formData.tel)) {
        uni.showToast({
          title: '请输入正确的手机号码',
          icon: 'none'
        });
        return false;
      }
      if (!this.formData.address || this.formData.address.trim() === '') {
        uni.showToast({
          title: '请输入所在地区',
          icon: 'none'
        });
        return false;
      }
      if (!this.formData.desc || this.formData.desc.trim() === '') {
        uni.showToast({
          title: '请输入详细地址',
          icon: 'none'
        });
        return false;
      }
      return true;
    },
    // 保存地址
    async handleSave() {
      // 表单验证
      if (!this.validateForm()) {
        return;
      }

      // 准备提交数据
      const addressData = {
        name: this.formData.name.trim(),
        tel: this.formData.tel.trim(),
        address: this.formData.address.trim(),
        desc: this.formData.desc.trim(),
        default: this.formData.default
      };

      // 编辑模式传递id，新增模式不传id
      if (this.isEdit && this.addressId) {
        addressData.id = this.addressId;
      }

      try {
        uni.showLoading({
          title: '保存中...',
          mask: true
        });

        const res = await addressApi.saveAddress(addressData);
        console.log("保存地址结果:", res);

        uni.hideLoading();

        if (res.code === 1) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          });
          // 延迟返回，让用户看到成功提示
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: res.msg || '保存失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error("保存地址异常:", error);
        uni.hideLoading();
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.address-add-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 状态栏占位 */
.status-bar {
  width: 100%;
  background-color: #ffffff;
}

/* 自定义导航栏 */
.custom-nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
}

.nav-back {
  position: absolute;
  left: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 44px;
  height: 44px;
  z-index: 1001;
}

.nav-title {
  font-size: 18px;
  font-weight: 700;
  color: #333333;
}

/* 内容区域 */
.content-scroll {
  height: calc(100vh - 44px - 100rpx);
  margin-top: 44px;
  padding-bottom: 100rpx;
}

/* 表单容器 */
.form-container {
  background-color: #ffffff;
  margin-top: 20rpx;
}

/* 表单项 */
.form-item {
  display: flex;
  align-items: center;
  padding: 20rpx 20rpx;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
}

.form-item:last-child {
  border-bottom: none;
}

.form-label {
  font-size: 30rpx;
  color: #505050;
  width: 160rpx;
  flex-shrink: 0;
}

.form-input {
  flex: 1;
  font-size: 30rpx;
  color: #505050;
  min-width: 0;
}

/* 定位按钮 */
.location-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-left: 20rpx;
  padding: 10rpx 20rpx;
  flex-shrink: 0;
}

.location-icon {
  width: 22px;
  height: 22px;
}

.location-text {
  font-size: 32rpx;
  color: #505050;
}

/* 默认地址开关 */
.default-switch {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 20rpx;
  background-color: #ffffff;
  margin-top: 20rpx;
}

.switch-label {
  font-size: 30rpx;
  color: #333333;
}

/* 底部保存按钮 */
.save-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #ff0000;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.save-btn-text {
  font-size: 32rpx;
  color: #ffffff;
  font-weight: 500;
}
</style>
